<template>
  <div class="wrapper">
    <!-- 顶部导航 -->
    <header>
      <i class="fa fa-arrow-left" @click="router.push('/')"></i>
      <div class="title">我的订单</div>
      <div class="placeholder"></div>
    </header>

    <!-- 订单状态切换 -->
    <div class="order-tabs">
      <div 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="['tab-item', { active: currentTab === index }]"
        @click="currentTab = index"
      >
        {{ tab }}
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" v-if="orderList.length > 0">
      <div class="order-item" v-for="order in filteredOrders" :key="order.orderId">
        <!-- 商家信息 -->
        <div class="business-info">
          <div class="business-name">
            {{ businessInfo[order.businessId]?.businessName || '未知商家' }}
          </div>
          <div class="order-status">{{ getStatusText(order.orderState) }}</div>
        </div>

        <!-- 订单内容 -->
        <div class="order-content">
          <div class="food-list">
            <div class="food-item" v-for="(item, index) in order.orderDetailList" :key="index">
              <div class="food-info">
                <div class="food-name">
                  {{ foodInfo[item.foodId]?.foodName || '未知商品' }}
                </div>
                <div class="food-spec" v-if="foodInfo[item.foodId]?.foodSpec">
                  {{ foodInfo[item.foodId].foodSpec }}
                </div>
              </div>
              <div class="food-price-quantity">
                <span class="food-price">¥{{ foodInfo[item.foodId]?.foodPrice || item.price }}</span>
                <span class="food-quantity">x{{ item.quantity }}</span>
              </div>
            </div>
          </div>
          <div class="total-price">
            <span>共{{ getTotalQuantity(order.orderDetailList) }}件商品</span>
            <span>配送费 ¥{{ businessInfo[order.businessId]?.deliveryPrice || 0 }}</span>
            <span>实付 ¥{{ order.orderTotal }}</span>
          </div>
        </div>

        <!-- 订单操作 -->
        <div class="order-actions">
          <el-button size="small" type="info" plain @click="toOrderDetail(order.orderId)">
            查看详情
          </el-button>
          <template v-if="order.orderState === 0">
            <el-button size="small" @click="cancelOrder(order)">取消订单</el-button>
            <el-button type="primary" size="small" @click="toPayment(order.orderId)">去支付</el-button>
          </template>
          <template v-else-if="order.orderState === 1">
            <el-button 
              v-if="!order.isReviewed"
              size="small" 
              @click="handleConfirm(order)"
            >
              确认收货
            </el-button>
          </template>
          <template v-else-if="order.orderState === 2">
            <el-button 
              size="small" 
              @click="toReview(order)" 
              v-if="!order.isReviewed"
            >评价</el-button>
            <el-button size="small" disabled v-else>已评价</el-button>
            <el-button size="small" @click="deleteOrder(order)">删除订单</el-button>
          </template>
          <template v-else-if="order.orderState === 3">
            <el-button size="small" @click="deleteOrder(order)">删除订单</el-button>
          </template>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state" v-else>
      <i class="fa fa-file-text-o"></i>
      <p>暂无相关订单</p>
    </div>

    <!-- 底部导航 -->
    <!-- <Footer></Footer> -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import Footer from '../components/Footer.vue'
import { getOrdersByUserId, updateOrderStatus } from '../api/orders'
import { getBusinessByIdService } from '../api/business'
import { getFoodByIdService } from '../api/food'
import { useUserInfoStore } from '../stores/user'
import { listOrderDetails } from '../api/orderDetail'
import { cancelOrderApi } from '../api/orders'
import { confirmOrder } from '@/api/orders'

const router = useRouter()
const route = useRoute()
const orderList = ref([])
const currentTab = ref(0)
const userInfoStore = useUserInfoStore()

// 订单状态标签
const tabs = ['全部', '待支付', '待收货', '已完成']

// 订单状态文本
const orderStateText = {
  0: '待支付',
  1: '配送中',
  2: '已完成',
  3: '已取消'
}

// 根据当前标签筛选订单
const filteredOrders = computed(() => {
  if (currentTab.value === 0) return orderList.value
  
  return orderList.value.filter(order => {
    switch (currentTab.value) {
      case 1: // 待支付
        return order.orderState === 0
      case 2: // 待收货 
        return order.orderState === 1
      case 3: // 已完成
        return order.orderState === 2
      default:
        return false
    }
  })
})

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '配送中',
    2: '已完成',
    3: '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 计算订单总数量
const getTotalQuantity = (details = []) => {
  return details.reduce((sum, item) => sum + (item.quantity || 0), 0)
}

// 存储商家和食品信息的响应式对象
const businessInfo = ref({})
const foodInfo = ref({})

// 修改加载订单列表的方法
const loadOrders = async () => {
  try {
    const userId = userInfoStore.userInfo.id
    
    if (!userId) {
      console.error('用户ID不存在')
      return
    }

    const res = await getOrdersByUserId(userId)
    if (res.code === 0 && Array.isArray(res.data)) {
      
      // 先获取所有订单详情
      const orderDetailsResponse = await listOrderDetails()
      
      // 将订单详情按订单ID分组
      const orderDetailsMap = {}
      if (orderDetailsResponse.code === 0 && Array.isArray(orderDetailsResponse.data)) {
        orderDetailsResponse.data.forEach(detail => {
          const orderId = detail.orderId;
          if (!orderDetailsMap[orderId]) {
            orderDetailsMap[orderId] = []
          }
          orderDetailsMap[orderId].push(detail)
        })
      }
      
      // 将订单详情添加到对应的订单中
      const ordersWithDetails = res.data.map(order => {
        const orderId = order.orderId || order.id;
        return {
          ...order,
          orderDetailList: orderDetailsMap[orderId] || []
        }
      })
      
      orderList.value = ordersWithDetails // 保持原有顺序
      
      // 获取商家和食品信息
      await fetchBusinessInfo()
      await fetchFoodInfo()
    } else {
      console.warn('获取订单列表失败或数据格式不正确')
      orderList.value = []
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
    orderList.value = []
  }
}

// 获取商家信息
const fetchBusinessInfo = async () => {
  try {
    if (!orderList.value || !Array.isArray(orderList.value)) {
      return;
    }

    const businessIds = [...new Set(orderList.value.map(order => order.businessId))]

    if (businessIds.length === 0) {
      return;
    }

    for (const businessId of businessIds) {
      if (!businessId) continue;
      
      const response = await getBusinessByIdService({ businessId });
      if (response.code === 0) {
        businessInfo.value[businessId] = response.data;
      }
    }
  } catch (error) {
    ElMessage.error('获取商家信息失败');
  }
};

// 获取食品信息
const fetchFoodInfo = async () => {
  try {
    if (!orderList.value || !Array.isArray(orderList.value)) {
      return;
    }

    const foodIds = [...new Set(orderList.value.flatMap(order => {
      const details = order.orderDetailList || [];
      return details.map(detail => detail.foodId);
    }))].filter(id => id != null);

    if (foodIds.length === 0) {
      return;
    }

    for (const foodId of foodIds) {
      const response = await getFoodByIdService(foodId);
      if (response.code === 0) {
        foodInfo.value[foodId] = response.data;
      }
    }
  } catch (error) {
    ElMessage.error('获取食品信息失败');
  }
};

// 取消订单
const cancelOrder = async (order) => {
  try {
    const orderId = order.orderId  || order.id;
    
    if (!orderId) {
      ElMessage.error('订单信息有误');
      return;
    }

    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const response = await cancelOrderApi(orderId);
    
    if (response.code === 0) {
      ElMessage.success('订单已取消');
      await loadOrders();
    } else {
      ElMessage.error(response.message || '取消订单失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败');
    }
  }
};

// 确认收货
const handleConfirm = async (order) => {
  try {
    const res = await confirmOrder(order.orderId, order.businessId)
    if (res.code === 0) {
      ElMessage.success('确认收货成功')
      // 刷新订单列表
      await loadOrders()
      // 切换到已完成订单标签
      currentTab.value = 3  // 对应"已完成"标签的索引
    }
  } catch (error) {
    ElMessage.error('确认收货失败')
    console.error(error)
  }
};

// 添加跳转支付页面的方法
const toPayment = (orderId) => {
  // 从订单列表中找到对应的订单
  const currentOrder = orderList.value.find(order => 
    order.orderId === orderId || order.orderid === orderId || order.id === orderId
  );

  if (!currentOrder) {
    ElMessage.error('订单信息有误');
    return;
  }

  router.push({
    path: '/payment',
    query: {
      orderId: orderId,
      addressId: currentOrder.daId || currentOrder.addressId // 兼容不同的属性名
    }
  });
};

// 查看配送
const viewDelivery = (order) => {
  // 跳转到配送详情页面
  router.push({
    path: '/delivery',
    query: { orderId: order.orderId }
  })
}

// 写评价
const writeReview = (order) => {
  // 跳转到评价页面
  router.push({
    path: '/review',
    query: { orderId: order.orderId }
  })
}

import { deleteOrderApi } from '../api/orders'

// 删除订单
const deleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该订单吗？此操作不可恢复',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    const response = await deleteOrderApi(order.orderId || order.id);
    if (response.code === 0) {
      ElMessage.success('订单已删除');
      await loadOrders();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除订单失败');
    }
  }
};

// 显示操作按钮的逻辑
const showOrderActions = (orderState) => {
  return {
    showPay: orderState === 0,      // 未支付状态显示支付按钮
    showCancel: orderState === 0,    // 未支付状态显示取消按钮
    showConfirm: orderState === 1,   // 配送中状态显示确认收货按钮
    showDelete: orderState === 2 || orderState === 3  // 已完成或已取消状态显示删除按钮
  }
}

// 在组件挂载时，根据路由参数设置当前选中的标签
onMounted(() => {
  const tab = parseInt(route.query.tab, 10)
  if (!isNaN(tab)) {
    currentTab.value = tab
  }
  loadOrders()
})

const toAddressPage = () => {
  router.push({
    path: '/address',
    query: { from: 'order' }
  });
};

// 跳转到评价页面
const toReview = (order) => {
  router.push({
    path: '/review',
    query: {
      orderId: order.orderId || order.id,
      businessId: order.businessId
    }
  });
};

// 添加跳转到订单详情的方法
const toOrderDetail = (orderId) => {
  router.push({
    path: '/order-detail',
    query: { 
      orderId,
      from: 'order' // 添加来源标记
    }
  })
}
</script>

<style scoped lang="scss">
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 14vw;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 4vw;
  background-color: #ff7043;
  position: sticky;
  top: 0;
  z-index: 1000;
}

header .fa-arrow-left {
  font-size: 4vw;
  color: #fff;
  width: 8vw;
  cursor: pointer;
}

header .title {
  font-size: 4.5vw;
  font-weight: bold;
  color: #fff;
}

header .placeholder {
  width: 8vw;
}

.order-tabs {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 3vw 0;
  margin-bottom: 2vw;
}

.tab-item {
  font-size: 3.8vw;
  color: #666;
  padding: 1vw 2vw;
  cursor: pointer;
}

.tab-item.active {
  color: #ff7043;
  position: relative;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1vw;
  left: 50%;
  transform: translateX(-50%);
  width: 4vw;
  height: 0.5vw;
  background-color: #ff7043;
  border-radius: 0.25vw;
}

.order-list {
  padding: 0 3vw;
}

.order-item {
  background-color: #fff;
  border-radius: 2vw;
  margin-bottom: 3vw;
  padding: 3vw;
}

.business-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 2vw;
  border-bottom: 1px solid #eee;
}

.business-name {
  font-size: 4vw;
  font-weight: bold;
}

.order-status {
  font-size: 3.5vw;
  color: #ff7043;
}

.order-content {
  padding: 2vw 0;
}

.food-list {
  margin-bottom: 2vw;
}

.food-item {
  display: flex;
  justify-content: space-between;
  font-size: 3.5vw;
  color: #666;
  margin-bottom: 1vw;
}

.total-price {
  text-align: right;
  font-size: 3.5vw;
  color: #333;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 12px 15px;
  border-top: 1px solid #f5f5f5;
  gap: 10px;
}

:deep(.el-button) {
  margin-left: 0 !important;
  
  &.el-button--small {
    padding: 8px 15px;
    font-size: 13px;
  }

  &.el-button--info.is-plain {
    border-color: #dcdfe6;
    color: #666;
    
    &:hover {
      color: #ff6b01;
      border-color: #ff6b01;
      background-color: #fff8f3;
    }
  }

  &.el-button--primary {
    background-color: #ff6b01;
    border-color: #ff6b01;
    
    &:hover {
      background-color: #ff8534;
      border-color: #ff8534;
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20vw 0;
  color: #999;
}

.empty-state i {
  font-size: 15vw;
  margin-bottom: 3vw;
}

.empty-state p {
  font-size: 4vw;
}

/* Element Plus 按钮样式覆盖 */
:deep(.el-button--small) {
  padding: 1.5vw 3vw;
  font-size: 3.5vw;
}

/* 支付按钮样式 */
:deep(.el-button--primary) {
  background-color: #ff7043 !important;
  border-color: #ff7043 !important;
}

.food-info {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.food-spec {
  font-size: 3vw;
  color: #999;
  margin-top: 0.5vw;
}

.food-price-quantity {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.food-price {
  color: #ff7043;
}

.total-price {
  display: flex;
  justify-content: flex-end;
  gap: 3vw;
  font-size: 3.5vw;
  color: #333;
}

.total-price span:last-child {
  color: #ff7043;
  font-weight: bold;
}
</style> 